import socketserver
import logging
import threading
import socket


logging.basicConfig(level=logging.INFO, format="%(asctime)s %(thread)d %(message)s")

class Myhandler(socketserver.StreamRequestHandler):
    def setup(self):
        super().setup()
        self.event = threading.Event()
        with self.server.sock:
            self.server.clients[self.client_address] = self

    def handle(self):
        super().handle()
        while not self.event.is_set():
            #logging.info(self.client_address)
            #logging.info(self.request)
            data = self.rfile.readline().decode().strip()
            if data == '' or data == 'quit':
                with self.server.sock:
                    self.server.clients.pop(self.client_address)
                break
            print(data)
            with self.server.sock:
                for v in self.server.clients.values():
                    msg = "{} client say {}".format(self.client_address,data).encode()
                    #self.wfile.write(msg)
                    v.wfile.write(msg)

    def finish(self):
        super().finish()
        self.event.set()
        with self.server.sock:
            if self.client_address in self.server.clients.keys():
                self.server.clients.pop(self.client_address)

server = socketserver.ThreadingTCPServer(('127.0.0.1', 9999), Myhandler)
server.daemon_threads = True
server.sock = socket.socket()
server.clients = {}
threading.Thread(target=server.serve_forever, name=server, daemon=True).start()

while True:
    cmd = input('input:').strip()
    if cmd == 'quit':
        server.server_close()
        break
    print(threading.enumerate())
    print(server.clients.keys())

